<?php

/**
  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; version 3 of the License.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.
 */
/**
 * Gmaps coordinate handler class
 * @package Util
 * @author Vincze Tamás
 * @version 0.1
 */

namespace Util;

class Gmaps {

	protected static $_baseURL = "http://maps.google.com/maps/api/geocode/";

	/**
	 * Gets XML data from google maps, and parses the XML to get the locations
	 * @param array|string $address
	 * @return array
	 */
	protected static function _getLocationsByXML($address) {
		if (is_array($address)){
			$address = join(",", $address);
		}

		$xml = simplexml_load_file(self::$_baseURL . "xml?sensor=false&address=$address", 'SimpleXMLElement', LIBXML_NOCDATA);
		$results = $xml->xpath("/GeocodeResponse/result/geometry/location");
		$return = array();
		foreach ($results as $result){
			$return[] = array((float) $result->lat, (float) $result->lng);
		}
		return $return;
	}

	/**
	 * Get first coordinates of the address
	 * @param array $address simple array: array($latitude1, $longitude1)
	 */
	public static function getCoordinates($address) {
		$coordinates = self::_getLocationsByXML($address);
		if (isset($coordinates[0])){
			return $coordinates[0];
		} else {
			return array();
		}
	}

	/**
	 * Get all coordinates of the address
	 * @param array|null $address nested array: array(array($latitude1, $longitude1), array($latitude2, $longitude2)) or null on error
	 */
	public static function getAllCoordinates($address) {
		return self::_getLocationsByXML($address);
	}

	/**
	 * Get address from coordinates
	 * @param array|float $coordinates
	 * @param null|float $longitude
	 */
	public static function getAddress($coordinates, $longitude = null){
		if (is_array($coordinates) && isset($coordinates[1])){
			$latitude = $coordinates[0];
			$longitude = $coordinates[1];
		} else {
			$latitude = $coordinates;
		}

		$xml = simplexml_load_file("http://maps.google.com/maps/api/geocode/json?address=$latitude,$longitude&sensor=false", 'SimpleXMLElement', LIBXML_NOCDATA);
		// TODO get address
	}


}

?>
